package com.wteam.security.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.wteam.framework.common.security.token.TokenUtils;
import com.wteam.framework.common.security.token.myTokenUtil;
import com.wteam.until.Result;
import com.wteam.until.UserContext;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
public class JWTCheck implements HandlerInterceptor {
    @Override//目标方法执行前，返回Boolean
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {

        System.out.println("preHandle执行了");


        //1.获取请求url
        String url = req.getRequestURI().toString();
        log.info("请求url:{}", url);
        //2判断请求url是否包含login，如果包含放行
        if (url.contains("login") || url.contains("/regist")) {
            log.info("登录放行：{}");
            return true;
        }

        //3看请求头令牌是否存在
        String jwt1 = req.getHeader("token");
        if (!StringUtils.hasLength(jwt1)) {
            log.info("请求头为空");
            Result error = Result.error(409, "Token_is_null");
            //手懂转换jasn格式
            String s = JSONObject.toJSONString(error);
            resp.getWriter().write(s);

            return false;
        }

//4看令牌是否出错
        try {
            //获取用户id
            Map<String, Object> claims = myTokenUtil.parseJWT(jwt1);

            Long id = (Long) claims.get("id");
            //将用户id存到当前线程
            UserContext.setUser(id);
            log.info(id+"用户ID");
        } catch (Exception e) {
            log.info("假的令牌Jwt反问");
            Result error = Result.error(409, "your_token_is_false");
            //手懂转换jasn格式
            String s = JSONObject.toJSONString(error);
            resp.getWriter().write(s);
            return false;
        }

        log.info("令牌合法");
        return true;
    }

    @Override//目标方法执行后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");

    }

    @Override//视图渲染后，最后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCOmpletion");
        // 清理用户
        UserContext.removeUser();
    }
}
